<template>
  <div>
    <div class="title">
      <span>基本信息</span>
      <div>
          <el-button icon="el-icon-refresh" @click="refresh"></el-button>
      </div>
    </div>

    <div class="container">
      <div class="itemBox">
        <div class="line">
        <div>商户号</div>
        <div>{{merSplitInfo.merchantNo}}</div>
        </div>
        <div class="line">
        <div>商户名</div>
        <div>{{merSplitInfo.merchantName}}</div>
        </div>
      </div> 
      <div class="itemBox">
        <div class="line">
        <div>通道名称</div>
        <div>{{merSplitInfo.channelName}}</div>
        </div>
      </div>

      <!-- 分账配置 -->
      <div class="splitBox">
        <el-button type="primary" @click="openMerSplit">配置默认分账</el-button>
      </div>

      <!-- 分账配置 -->
      <el-dialog
          title="默认分账配置"
          center
          :visible.sync="merSplitVisible"
          @closed="merSplitClose"
          @opened="onOpen"
          width="1000px"
          :close-on-click-modal="false">
          <el-form ref="merSplitForm" class="split-form" label-position="left" label-width="100px" :model="merSplitForm" :rules="merSplitFormRules">
            <div class="merSplit">
              <el-form-item class="ipt" prop="merchantName" label="分账商户名">
              <el-autocomplete
              style="width: 90%"
              v-model.trim="merSplitForm.merchantName"
              :fetch-suggestions="merchantslist"
              :trigger-on-focus="false"
              :debounce="300"
              placeholder="分账商户名"
              disabled
              @select="okmerchants">
            </el-autocomplete>
            </el-form-item>
            <el-form-item class="ipt" prop="channelId" label="通道类型">
              <el-select style="width: 90%;" disabled v-model="merSplitForm.channelName"  placeholder="通道类型" @change="channelChange">
                <el-option v-for= '(item) in channelinfo' :key='item.channelId' :label='item.channelName' :value="item.channelId"></el-option>
              </el-select>
            </el-form-item>
            </div>
            <div class="feeMerchant">
              <div class="split-box">
              <div>
                <el-form-item class="ipt" prop="percent" label-width="0">
                  <el-input placeholder="请输入分账比例" style="width: 100%;" v-model.number.trim="merSplitForm.percent"></el-input>
                </el-form-item>
                <div style="margin: 5px 0 0px 0px; font-size: 13px;">
                  <i class="el-icon-question" style="margin-right: 5px"></i>
                  <span class="ratio-tips">分账比例取值范围（%）：0.01~100，可精确到2位小数</span>
                </div>
              </div>
              <div style="margin-left: 10px;">
                <el-form-item label-width="0">
                  <el-autocomplete
                    style="width: 60%;"
                    v-model.trim="bySplitMer.merchantName"
                    :fetch-suggestions="bymerchantslist"
                    :trigger-on-focus="false"
                    :debounce="300"
                    placeholder="被分账商户"
                    @select="okBymerchants">
                  </el-autocomplete>
                  <el-button type="primary" style="margin-left: 10px" @click="addBySplitMer"><i class="el-icon-lx-add"></i>添加</el-button>
                </el-form-item>
              </div>
              </div>
                <el-table
                  ref="singleTable"
                  :data="bySplitData"
                  @select="select"
                  :loading="dialogLoading"
                  :header-cell-style="tableHeaderColor"
                  style="width: 100%; margin-top: 20px;">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column
                    prop="merchantName"
                    label="商户名">
                  </el-table-column>
                  <el-table-column
                    prop="merchantNo"
                    label="商户号">
                  </el-table-column>
                  <el-table-column
                    prop="percent"
                    label="分账比例(%)">
                  </el-table-column>
                  <el-table-column
                      fixed="right"
                      align="center"
                      label="操作"
                      width="60">
                      <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click="deletMerSplitFn(scope.row)">
                            删除
                        </el-button>
                      </template>
                  </el-table-column>
                </el-table>
                <div style="margin: 5px 0 5px 0px; font-size: 13px;">
                  <i class="el-icon-question" style="margin-right: 5px"></i>
                  <span class="ratio-tips">勾选被分账商户为手续费承担方，不勾选默认分账方为手续费承担方</span>
                </div>
                <el-form-item style="text-align:right; margin-top: 20px;">
                  <el-button type="primary" @click="onSubmit">确定</el-button>
                  <el-button @click="merSplitClose">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-dialog>

      <!-- 被分账商户表格 -->
      <div class="tableBox" v-if="isShowTable">
        <el-table
          ref="multipleTable"
          :data="merSplitInfo.splitMerchantInfos"
          tooltip-effect="dark"
          stripe
          style="width: 100%"
          v-loading="loading">
        <el-table-column
            prop="merchantNo"
            label="商户号"
            align="center">
        </el-table-column>
        <el-table-column
            prop="merchantName"
            label="商户名"
            align="center">
        </el-table-column>
        <el-table-column
            prop="percent"
            label="分账比例（%）"
            align="center">
        </el-table-column>
      </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { merSplitDetail, updateMerSplit } from '@/api/defaultsplit/defaultsplit.js'
import { merchantlist } from '@/api/api'
import { getMerSplitChannelInfo } from '@/api/splitrelation/splitrelation.js'
export default {
  name: 'DefaultsplitDetail',

  data() {
    var checkPercent = (rule, value, cb) => {
      console.log(value);
    if(this.merSplitInfo.splitMerchantInfos.length > 0 && this.bySplitMer.merchantName == undefined) {
      return cb()
    }
      // 分账比例的正则表达式
    const regRatio = /^(0\.(0[1-9]|[1-9]\d{0,1})|[1-9]\d{0,1}(\.\d{1,2})?|100(\.0{1,2})?)$/
    if (regRatio.test(value)) {
      //合法的分摊比例
      return cb()
    }
    cb(new Error('请填写正确的分摊比例'))
    }
    return {
      merSplitFormRules: {
        merchantName: [
          { required: true, message: '请选择分账商户', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择通道类型', trigger: 'change' }
        ],
        percent: [
          { validator: checkPercent, trigger: 'blur' }
        ],
        // feeMerchantId: [
        //   { validator: checkFeeMerchantiId, trigger: '' }
        // ]
      },
      userinfo: {},
      merSplitId: '',
      merSplitInfo: {},
      merSplitForm: {
        merchantName: '',
        percent: '',
      },
      merchantarrlist: [],
      channelinfo: [],
      loading: false,
      isShowTable: false,
      merSplitVisible: false,
      bySplitMer: {},
      bySplitData: [],
      rows: [],
      dialogLoading: false,
    };
  },

  watch: {
    $route(){
      if(this.$route.path=='/defaultsplitdetail'){
        this.merSplitId = sessionStorage.getItem('merSplitId')
        this.merSplitDetailFn()
      }
    }
  },

  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.merSplitId = sessionStorage.getItem('merSplitId')
    this.merSplitDetailFn()
  },

  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
            return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
        }
    },
    // 刷新
    refresh() {
      this.merSplitDetailFn()
    },
    // 查询默认分账详情信息
    async merSplitDetailFn() {
      let res = await merSplitDetail(this.merSplitId)
      if(res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.merSplitInfo = res.data
        if(this.merSplitInfo.splitMerchantInfos.length > 0) {
          this.isShowTable = true
        }
      }
    },
    // 获取商户列表初始化
    merchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.merSplitForm.merchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    // 被分账商户初始化
    bymerchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.bySplitMer.merchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    select(selection, row) {
      // 清除 所有勾选项
      this.$refs.singleTable.clearSelection()
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if(selection.length == 0) {
        this.merSplitForm.feeMerchantId = ''
        return
      }
      this.$refs.singleTable.toggleRowSelection(row, true);
      this.merSplitForm.feeMerchantId = row.merchantId
    },
    // 选择商户
    okmerchants(val) {
        console.log(val);
        // this.addCouponForm.merchantId = val.mid;
        this.merSplitForm.merchantId = val.merchantId;
        this.merSplitForm.merchantNo = val.merchantNo
        this.getChannelFn(val.merchantId)
    },
    // 选择商户
    okBymerchants(val) {
        console.log(val);
        // this.addCouponForm.merchantId = val.mid;
        this.bySplitMer.merchantId = val.merchantId;
        this.bySplitMer.merchantNo = val.merchantNo;
    },
    // 获取通道列表
    async getChannelFn(id) {
      let res = await getMerSplitChannelInfo(id)
      if(res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.channelinfo = res.data
      }
    },
    // 通道选中
    channelChange(val) {
      this.channelinfo.forEach((item,index) => {
        if(item.channelId == val) {
          this.merSplitForm.channelName = item.channelName
          this.merSplitForm.channelType = item.channelType
        }
      })
    },
    // 打开配置弹窗
    openMerSplit() {
      this.dialogLoading = true
      this.merSplitForm.merchantId = this.merSplitInfo.merchantId
      this.merSplitForm.merchantName = this.merSplitInfo.merchantName
      this.merSplitForm.merchantNo = this.merSplitInfo.merchantNo
      this.merSplitForm.id = this.merSplitInfo.id
      this.merSplitForm.channelId = this.merSplitInfo.channelId
      this.merSplitForm.channelName = this.merSplitInfo.channelName
      this.merSplitForm.channelType = this.merSplitInfo.channelType
      this.merSplitForm.feeMerchantId = this.merSplitInfo.feeMerchantId
      this.getChannelFn(this.merSplitInfo.merchantId)
      this.merSplitVisible = true
    },
    onOpen() {
      this.merSplitInfo.splitMerchantInfos.forEach((item, index) => {
        this.bySplitData.push({
          merchantId: item.merchantId,
          merchantName: item.merchantName,
          merchantNo: item.merchantNo,
          percent: item.percent,
        })
      })
      const TABLE_DOM = this.$refs.singleTable
      const { bySplitData } = this
      if(TABLE_DOM) {
        TABLE_DOM.clearSelection()
        this.$nextTick(()=>{
          TABLE_DOM.toggleRowSelection(bySplitData.find(item=>{
            return  item.merchantId == this.merSplitInfo.feeMerchantId  // 注意这里寻找的字段要唯一，示例仅参考
          }),true);
        })
      }
      this.dialogLoading = false
    },
    // 关闭配置弹窗
    merSplitClose() {
      this.$refs.merSplitForm.resetFields()
      this.$refs.singleTable.setCurrentRow('')
      this.merSplitForm.feeMerchantId = ''
      this.merchantarrlist = []
      this.channelinfo = []
      this.bySplitData = []
      this.bySplitMer = {}
      this.merSplitVisible = false
    },
    // 添加被分账商户
    addBySplitMer() {
      this.$refs.merSplitForm.validate(async(valid) => {
        if(valid) {
          if(this.bySplitMer.merchantId == this.merSplitForm.merchantId) {
            this.$message.error('被分账商户不能和分账商户相同')
            return
          } else if (this.bySplitData.some((item) => { return this.bySplitMer.merchantId == item.merchantId })) {
            this.$message.error('已存在相同的被分账商户')
            return
          } else if (this.bySplitMer.merchantName == undefined || this.bySplitMer.merchantName == ''){
            this.$message.error('请选择被分账商户')
            return
          } else {
            if(this.bySplitData.length > 0) {
              let total = 0
              this.bySplitData.forEach(item => {
                total += item.percent
              })
              if(total + this.merSplitForm.percent > 100) {
                this.$message.error('分账比例合计不能超过100')
                return
              }
            }
            // this.bySplitData.some((item) => { 
            //   console.log(this.bySplitMer.merchantId == item.merchantId);
            //  })
            this.bySplitMer.percent = this.merSplitForm.percent
            this.bySplitData.unshift({
              merchantId: this.bySplitMer.merchantId,
              merchantNo: this.bySplitMer.merchantNo,
              merchantName: this.bySplitMer.merchantName,
              percent: this.bySplitMer.percent,
            })
            this.merSplitForm.percent = undefined
            this.bySplitMer = {}
          }
        }
      })
    },
    // 提交
    onSubmit() {
        this.$refs.merSplitForm.validate(async(valid) => {
          if(valid) {
              let splitInfo = []
              this.bySplitData.forEach((item) => {
                splitInfo.push({
                  merchantId: item.merchantId,
                  percent: item.percent
                  })
                })
                let feeMerchantId = this.merSplitForm.feeMerchantId ? this.merSplitForm.feeMerchantId : this.merSplitForm.merchantId
                let list = {
                  id: this.merSplitForm.id,
                  merchantId: this.merSplitForm.merchantId,
                  merchantNo: this.merSplitForm.merchantNo,
                  merchantName: this.merSplitForm.merchantName,
                  channelId: this.merSplitForm.channelId,
                  channelType: this.merSplitForm.channelType,
                  channelName: this.merSplitForm.channelName,
                  splitInfo: JSON.stringify(splitInfo),
                  feeMerchantId: feeMerchantId
                }
                let res = await updateMerSplit(list)
                if(res.code == 405) {
                  sessionStorage.removeItem("token");
                  this.$router.push("/login");
                } else {
                  if(res.code == 200) {
                    this.$message.success('修改默认分账关系成功')
                    this.merSplitClose()
                    this.merSplitDetailFn()
                  } else {
                    this.$message.error(res.message)
                  }
                }
          }
        })
      },
      // 删除
      deletMerSplitFn(val) {
        let index = this.bySplitData.findIndex(item => item.merchantId == val.merchantId);
        this.bySplitData.splice(index, 1)
      }
  },
};
</script>

<style lang="less" scoped>
.title {
  background: #fff;
  padding: 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.container {
  width: 100%;
  display: flex;
  margin-bottom: 20px;
  box-sizing: border-box;
}
.container .itemBox {
  width: 50%;
}
.container .itemBox .line {
  width: 100%;
  display: flex;
  font-size: 14px;
  line-height: 200%;
}
.container .itemBox .line div:nth-child(1) {
  width: 20%;
  text-align: left;
}
.container .itemBox .line div:nth-child(2) {
  width: 80%;
  text-align: left;
  color: #888888;
}
.container {
  width: 100%;
  display: flex;
  margin-bottom: 20px;
  box-sizing: border-box;
  flex-wrap: wrap;
  .attachmentitem {
    width: 16.5%;
    text-align: center;
    margin-bottom: 20px;
    div {
      font-size: 14px;
      &:nth-child(1) {
        margin-bottom: 5px;
      }
    }
  }
  .tableBox{
    width: 100%;
    margin-top: 20px;
  }
  .splitBox {
    width: 100%;
    margin: 20px 0 10px 0;
  }
  // /deep/.feeMerchant .el-table__row {
  //   cursor: pointer;
  // }
}
.split-box{ 
  display: flex;
}
.split-box > div {
  width: 350px;
}
.split-box > div:nth-child(2) {
  width: 500px;
}
.feeMerchant{
  margin-top: 10px;
  border-top: 1px dashed #c0c4cc;
  padding: 20px 10px 0 10px;
}
/deep/.el-table__header-wrapper  .el-checkbox{
	display:none
}
</style>